home *** CD-ROM | disk | FTP | other *** search
- Path: edmr70.ccinet.ab.ca!user
- From: d_martin@biomira.com (Douglas Martin)
- Newsgroups: comp.lang.c
- Subject: Re: Newbie needs help w/ recursion
- Date: 20 Mar 1996 18:41:02 GMT
- Organization: Biomira Inc.
- Message-ID: <d_martin-2003961146130001@edmr70.ccinet.ab.ca>
- References: <4ikq6p$io1@impsets.dash.com>
- NNTP-Posting-Host: edmr70.ccinet.ab.ca
-
- In article <4ikq6p$io1@impsets.dash.com>, Jim Bosshardt <jbossha@dash.com>
- wrote:
-
- > Hi, I am new and am about to pull my hair out over the supposedly simple
- > recursion problem I have. The function is to take a number and raise it
- > to a neg or pos power and return the value to main(). I need to take
- > the following and make it a recursive function...
- >
- > double power (double a, float b)
- > {
- > double power = 1;
- ^^^^^^^^^^^^^^^^^
- Huh?! You don't want to declare power to be a local variable if you are
- going to call it! Leave this out entirely.
-
- > int i;
- >
- > if (a == 0)
- > pow = 0;
- > else if (b == 0)
- > pow = 1;
- > else if Ib > 0)
- ^^ Did you mean to have b rather than lb here?
- > {
- > for(i = 1; i <= b; i++)
- > pow *= a;
- > }
- > else if (b < 0)
- > {
- > b = -b;
- > for (i = 1; i <= b; i+)
- > pow *= a;
- > return 1/pow;
- > }
- > return pow;
- > }
- >
-
- Remember, if power is to be recursive, you must call power somewhere
- within power.
-
- Judging from your code, you also want b to be declared an int, not a float
- - note what happens in your code if you, for instance, say
- y:=power(2.0,2.5);
-
- Now, let's just consider positive integer exponents and leave the rest as
- an exercise.
-
-
- x to the power 0 is 1
- if n is greater than 0
- x to the power n is x times (x to the power (n-1))
-
- Now, translate that to C, add some stuff for negative exponents, and you're off.
-
- --
- Douglas Martin d_martin@biomira.com
- Clinical Support Programmer dmartin@freenet.edmonton.ab.ca
- Biomira Inc.
- 2011 - 94 St. Edmonton
-